package com.fairytask.ui.load
{
	import com.fairytask.engine.GameStage;
	import com.fairytask.engine.data.BaseData;
	import com.fairytask.engine.event.LogicEvent;
	import com.fairytask.engine.managers.ResManager;
	import com.fairytask.engine.resource.StaticIni;
	import com.fairytask.engine.utils.IO;
	import com.fairytask.ui.base.FrameUI;
	
	import flash.display.Loader;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.ProgressEvent;
	import flash.events.TextEvent;
	import flash.external.ExternalInterface;
	import flash.net.URLRequest;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFormat;
	import flash.utils.getTimer;
	
	import fairy.events.OperationEvent;
	import fairy.operation.load.LoadOper;
	import fairy.operation.load.QueueLoadOper;

	/**
	 * 资源加载UI 
	 * @author hanjy
	 */	
	public class ResLoadUI extends FrameUI
	{
		private static var _instance	:ResLoadUI;
		private var _maxCount:int;
		private var lastTime:int;
		private var loadRes:MovieClip;
		private var _allProcessBar	:MovieClip;//总进程加载进度条
		//每日一笑
		private var _jokeText			:TextField;
		//总加载进度
		private var _allProcessBarTxt	:TextField;
		
		private var queueLoad:QueueLoadOper;
		
		//当前网速
		private var _speedTxt			:TextField;
		//刷新提示文本
		private var _freshTxt			:TextField;
		private var _loadingStr:String;
		private var BAR_WIDTH:int = 600;
		
		public static function get instance():ResLoadUI
		{
			if(null==_instance)
			{
				_instance	=	new ResLoadUI();
			}
			return _instance;
		}
		
		public function ResLoadUI(popUI:Boolean=false)
		{
			super(popUI);
		}
		
		/**
		 * 初始化显示 
		 */
		override public function initGUI():void
		{
			initText();
		}
		
		/**
		 * 初始化队列 
		 */
		private function initQueue():void
		{
			queueLoad	=	new QueueLoadOper("",1,onLoaded);
			queueLoad.loadHelper.addEventListener(ProgressEvent.PROGRESS,onProgress);
			
			_maxCount	=	int(StaticIni.GetServerVar("LoadingConfig","total"));
			var loadArr	:Array	=	[];
			var idArr	:Array	=	[];
			var nameArr	:Array	=	[];
			var sizeArr	:Array	=	[];
			var loadItem	:BaseData;
			for (var i:int = 0; i < _maxCount; i++) 
			{
				loadItem	=	StaticIni.StrToObj(StaticIni.GetServerVar("LoadingConfig",i.toString()));
				loadArr.push(loadItem.GetProperties("path"));
				idArr.push(i.toString());
				nameArr.push(loadItem.GetProperties("path"));
				sizeArr.push(loadItem.GetProperties("size"));
			}
			queueLoad.loadResources(loadArr,idArr,nameArr,sizeArr);
		}
		
		protected function onLoadReady(event:Event):void
		{
			setLoadRes(event.target.content);
			beginQueue();
		}
		
		private function initText():void
		{
			var tf:TextFormat = new TextFormat();
			tf.font	=	"微软雅黑";
			tf.size = 14;
			_speedTxt = new TextField();
			_speedTxt.selectable = false;
			_speedTxt.textColor = 0xffffff;
			_speedTxt.autoSize = TextFieldAutoSize.LEFT;
			_speedTxt.x = 832;
			_speedTxt.y = 480;
			_freshTxt = new TextField();
			_speedTxt.defaultTextFormat = _freshTxt.defaultTextFormat = tf;
			_freshTxt.selectable = false;
			_freshTxt.textColor = 0xffffff;
			_freshTxt.width = 250;
			_freshTxt.autoSize = TextFieldAutoSize.LEFT;
			_freshTxt.htmlText = "若当前加载速度过慢，请点击 <a href='event:fresh'><u><font color='#00ff00' textDecoration='underline'>刷新页面</u></a>";
			_freshTxt.x = (GameStage.rootW - _freshTxt.textWidth)/2;
			_freshTxt.y = 520;
			_freshTxt.addEventListener(TextEvent.LINK,onFresh);
			
			addChild(_speedTxt);
			addChild(_freshTxt);
		}
		
		private function onFresh(evt:TextEvent):void
		{
			//调用js完成刷新
			ExternalInterface.call("refresh");
		}
		
		/**
		 * 正在加载 
		 * @param event
		 * 
		 */
		protected function onProgress(evt:ProgressEvent):void
		{
			//IO.traceLog("加载进度::::::",evt.bytesLoaded,evt.bytesTotal);
			setCurBarVal(StaticIni.getSwfLangStr("1000000368"), queueLoad.loadHelper.loadPercent*100,evt.bytesLoaded,evt.bytesTotal);
		}
		/**
		 * 设置当前模块进度条
		 * @param str
		 * @param val
		 * 
		 */		
		public function setCurBarVal(str:String,val:int,bytesLoaded:uint=0,bytesTotal:uint=0):void
		{
			switch(str)
			{
				case "1000000367":
					str	=	"正在加载背景图";
					break;
				case "1000000368":
					str	=	"正在加载配置文件";
					break;
				case "1000000369":
					str	=	StaticIni.getSwfLangStr(str);
					break;
			}
			_allProcessBarTxt.text = str +val+"%";
			//资源加载
			if(bytesTotal != 0)
			{
				var spendTime:uint = getTimer() - lastTime;
				if(spendTime == 0)
				{
					spendTime = 1;
				}
				_speedTxt.text = queueLoad.loadHelper.progressNeedTimeString;
				lastTime  = getTimer();
			}
			
			_allProcessBar["maskBar"].width = queueLoad.loadHelper.loadPercent * BAR_WIDTH;
			_allProcessBar["point"].x = queueLoad.loadHelper.loadPercent * BAR_WIDTH;
		}
		
		/**
		 * 当加载完毕时 
		 * @param evt
		 * 
		 */
		private function onLoaded(evt:OperationEvent):void
		{
			var itemOper	:LoadOper;
			//初始化内存
			var loadItem	:BaseData;
			for (var i:int = 0; i < queueLoad.opers.length; i++) 
			{
				itemOper	=	queueLoad.opers[i];
				loadItem	=	StaticIni.StrToObj(StaticIni.GetServerVar("LoadingConfig",itemOper.id));
				if(loadItem.GetProperties("type")=="2")
				{
					StaticIni.initStaticFromObj(itemOper.loaderInfo.content);
				}
				if(loadItem.GetProperties("type")=="1")
				{
					ResManager.setOutRes(loadItem.GetProperties("path"),itemOper.loaderInfo.content);
				}
				
			}
			
			//应该可以结束了
			model.sendLogicEvent(LogicEvent.RESLOADED);
			this.hide();
		}
		
		/**
		 * 开始队列 
		 */
		public function beginQueue():void
		{
			if(loadRes==null)
			{
				if(GameStage.isLocal&&loadRes==null)
				{
					var loader	:Loader	=	new Loader();
					loader.contentLoaderInfo.addEventListener(Event.COMPLETE,onLoadReady);
					loader.load(new URLRequest("res/swf/loading.swf"));
				}
				return;
			}
			initQueue();
			queueLoad.execute();
			show();
		}
		
		public function setLoadRes(val:MovieClip):void
		{
			loadRes	=	val;
			addChild(loadRes);
			_allProcessBar	=	val["allProcessBar"];
			_jokeText		= 	val["jokeTxt"];
			_allProcessBarTxt = val["allProcessBarTxt"];
		}
		
		override public function show(space:String=LOGINLAYER, onshow:Function=null):void
		{
			super.show(space);
		}
	}
}